<template>
    <div class="ImageCropper disp-ib">

        <input type="file" ref="file" v-show="false" @change="fileChange"></input>
        <el-button
                type="primary"
                @click="start"
                v-if="showButton"
                :icon="buttonIcon"
                :disabled="buttonDisabled"
        >{{ buttonText }}
        </el-button>
        <el-dialog
                :visible.sync="visible"
                width="540px"
                :modal-append-to-body="true"
                :append-to-body="true"
                :close-on-click-modal="false"
        >
            <div class="mt-sm" style="height: 500px; ">
                <vue-cropper
                        ref="cropper"
                        :img="image"
                        :max-img-size="600"
                        output-type="png"
                        :auto-crop="autoCrop"
                        :fixed="fixed"
                        :fixed-number="fixedNumber"
                ></vue-cropper>
            </div>
            <div class="text-center mt-md">
                <el-button-submit
                        class="disp-ib"
                        :is-block="false"
                        @click.native="clickFinishCropper"
                >完成截图选择
                </el-button-submit>
            </div>

        </el-dialog>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Watch, Vue } from 'vue-property-decorator'
import ElButtonSubmit from "@/components/common/button/ElButtonSubmit"
import ImageUtil from "@/util/ImageUtil"
import DialogUtil from "@/util/DialogUtil"

@Component({
  components: {
    ElButtonSubmit
  }
})
export default class ImageCropper extends Vue {
  @Prop({
    default: true
  })
  readonly showButton!: any
  @Prop({
    default: '选择图片'
  })
  readonly buttonText!: any
  @Prop({
    default: 'iconfont icon-plus'
  })
  readonly buttonIcon!: any
  @Prop({
    default: false
  })
  readonly buttonDisabled!: any
  @Prop({
    default: true
  })
  readonly fixed!: any
  @Prop({
    default() {
      return [1, 1]
    }

  })
  readonly fixedNumber!: any
  @Prop({
    default: true
  })
  readonly autoCrop!: any
  visible: boolean = false
  image: any = this.img

  mounted() {
    this.reload()
  }

  reload() {}

  start() {
    (this.$refs.file as any).click()
  }

  fileChange(event) {
    ImageUtil.fileInputChange(event).then(img => {
      this.visible = true
      this.image = img
    }).catch(err => DialogUtil.toastWarning(err)).finally(() => (this.$refs.file as any).value = '')
  }

  clickFinishCropper() {
    (this.$refs.cropper as any).getCropData(data => {
      this.visible = false
      this.$emit('finish', data)
    })
  }

}
</script>

<style lang="less" scoped>
    @import "~style/var.less";

    .ImageCropper {
    }
</style>